<?php

namespace App\Http\Models;

use App\Http\Controllers\Controller;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Laravel\Lumen\Auth\Authorizable;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    public static function myFriends($uid) {
        $get_friends = Redis::GET('LyfenFriend:' . $uid);
        $friends = explode(',', $get_friends);

        $friend_list = [];
        foreach ($friends as $f) {
            $f_arr = explode('^', $f);
            if (count($f_arr) == 6) {
                $friend_list[] = [
                    'uid' => intval($f_arr[0]),
                    'duckId' => $f_arr[5] ?? 0,
                    'nickName' => $f_arr[3],
                    'avatar' => $f_arr[4],
                    'usedStar' => intval($f_arr[2]),
                ];
            }
        }

        return $friend_list;
    }

    public static function getMaxFodder($level) {

    }

    public static function getDropRound($uid) {
        $drop_round = null;
        $find_droparound = DB::table('droparounds')->where('friendUserId', $uid)->where('stealTime', '>', 0)->first();
        if(isset($find_droparound['id']) && $find_droparound['friendUserId'] >= 0) {
            $finfo = DB::table('users')->where('id', $find_droparound['id'])->first();
            if(isset($finfo['id'])) {
                $fduck = DB::table('ducks')->where('id', $finfo['duckId'])->first();
                if(isset($fduck['id'])) {
                    $drop_round = [
                        'uid' => $finfo['id'],
                        'dressupId' => $fduck['dressupId'],
                        'nickName' => $finfo['nickName'],
                        'avatar' => $finfo['avatar'],
                    ];
                }
            }
        }
        return $drop_round;
    }

    public static function checkStar($uid, &$duck_info, $save=true) {
        $now = \App\Http\Controllers\Controller::now();
        if($duck_info['feedCount'] >= config('game.cfg.BasePerProductStarFeedCount')
            && $duck_info['nextFeedTime'] != 0
            && $now >= $duck_info['nextFeedTime']) {
            $duck_info['nextFeedTime'] = 0;
            $star_num = intval($duck_info['feedCount'] / config('game.cfg.BasePerProductStarFeedCount'));
            $duck_info['feedCount'] = $duck_info['feedCount'] % config('game.cfg.BasePerProductStarFeedCount');
            $duck_info['waitGainStar'] += $star_num;
            if($save) {
                DB::table('ducks')->where('id', $duck_info['id'])->update([
                    'feedCount' => $duck_info['feedCount'],
                    'nextFeedTime' => $duck_info['nextFeedTime'],
                    'waitGainStar' => $duck_info['waitGainStar'],
                ]);
            }
            // 增加一条记录
            Record::new($uid, config('game.cfg.BaseRecordTypeNormal'), config('game.cfg.BaseRecordProductEgg'), [$star_num]);
        }
    }

    public static function refreshFodder($uid, &$duck_info=null, $save=false, $from='') {
        $now_sec = time();

        if($duck_info === null) {
            $user_info = DB::table('users')->where('id', $uid)->first();
            $duck_info = DB::table('ducks')->where('id', $user_info['duckId'])->first();
        }

        $steal_fodder = 0;

        // 获取别人鸭子来偷吃信息
        $steal_uid  = null;
        $find_steal = null;
        $find_steal = DB::table('droparounds')->where('friendUserId', $uid)->first();
        if(isset($find_steal['id']) && $find_steal['friendUserId'] > 0) {
            $steal_uid = $find_steal['friendUserId'];
        }

        # $second_one_gram : 多少秒一克
        $second_one_gram = round(config('game.cfg.BasePerDigestionTime') / config('game.cfg.BasePerFeedConsume'), 3);
        if($duck_info['updateFeedTime'] > 0) {
            $spend_time = $now_sec - $duck_info['updateFeedTime'];
            // 改成计算时间
            # $consumption_fodder : 消耗了多少饲料
            $consumption_fodder = intval($spend_time / $second_one_gram);
            if($consumption_fodder > $duck_info['leftFodder']) {
                $consumption_fodder = $duck_info['leftFodder'];
            }
            // var_dump($consumption_fodder);
            $duck_info['leftFodder'] -= $consumption_fodder;
            $duck_info['feedCount'] += $consumption_fodder;
            $duck_info['updateFeedTime'] += intval($consumption_fodder*$second_one_gram);

            // 好友1秒偷吃1g
            if( $steal_uid && $duck_info['leftFodder'] > 0 && $spend_time > 1) {
                if($spend_time > $duck_info['leftFodder']) {
                    $spend_time = $duck_info['leftFodder'];
                }

                $find_steal['updateTime'] += $spend_time;
                $find_steal['stealFodder'] += $spend_time;
                $duck_info['leftFodder'] -= $spend_time;
                $steal_fodder += $spend_time;
            }

            if($steal_uid && $steal_fodder > 0) {
                // 更新偷吃鸭子的数据 和累加好友feedCount
                DB::table('droparounds')->where('id', $find_steal['id'])->update([
                    'updateTime' => $find_steal['updateTime'],
                    'stealFodder' => $find_steal['stealFodder'],
                ]);
                DB::table('ducks')->where('id', $find_steal['friendDuckId'])->increment('feedCount', $steal_fodder);
            }
        }
        // 剩下饲料可食用秒数
        if($duck_info['leftFodder'] > 0) {
            // $duck_info['lastFeedTime'] = config('game.cfg.BasePerDigestionTime') - ((config('game.cfg.BasePerFeedConsume') - $duck_info['leftFodder']) * 90) -  ($now_sec - $duck_info['updateFeedTime']);
            $duck_info['lastFeedTime'] = ceil($second_one_gram * $duck_info['leftFodder']);
        } else {
            $duck_info['lastFeedTime'] = 0;
        }

        // 检查是否可以增加星星
        if($duck_info['feedCount'] >= config('game.cfg.BasePerProductStarFeedCount')) {
            $duck_info['feedCount'] -= config('game.cfg.BasePerProductStarFeedCount');
            $duck_info['waitGainStar']++;
            // 增加一条记录
            Record::new($uid, config('game.cfg.BaseRecordTypeNormal'), config('game.cfg.BaseRecordProductEgg'), [1]);
        }

        if($save === true) {
            DB::table('ducks')->where('id', $duck_info['id'])->update([
                'feedCount' => $duck_info['feedCount'],
                'leftFodder' => $duck_info['leftFodder'],
                'updateFeedTime' => $duck_info['updateFeedTime'],
                'waitGainStar' => $duck_info['waitGainStar'],
                'lastFeedTime' => $duck_info['lastFeedTime'],
            ]);
        }

        return $steal_fodder;
    }

    public static function levelUp( $uid ) {
        $uinfo = DB::table('users')->where('id', $uid)->first();
        $extra_exp = 0;
        if($uinfo['level'] < 1) {
            $uinfo['level'] ++;
        } else {
            if($uinfo['extra_exp']) {
                $extra_exp = $uinfo['extra_exp'] / 10;
            }
            $addExpOnce = round(config('game.cfg.LevelMaxExp') / config('game.cfg.LevelMaxFeedTimes'), 2);
            $currentOnce = intval($addExpOnce + $extra_exp);
            if($addExpOnce > $currentOnce) $extra_exp = intval(($addExpOnce - $currentOnce) * 10);
            else $extra_exp = 0;
            $uinfo['exp'] += $currentOnce;
            if($uinfo['exp'] >= config('game.cfg.LevelMaxExp')) {
                $uinfo['level']++;
                $uinfo['exp'] -= config('game.cfg.LevelMaxExp');
            }
        }
        DB::table('users')->where('id', $uid)->update([
            'level'=> $uinfo['level'],
            'exp'=> $uinfo['exp'],
            'extra_exp' => $extra_exp,
        ]);
        return ['level'=>$uinfo['level'], 'exp'=>$uinfo['exp']];
    }
}
